import requests
import json

# 获取 key 的方法
def getKey() -> str:
    try:
        with open("./API_KEYS/keys.json", 'r', encoding="utf-8") as f:
            jStr = json.load(f)
            return jStr['weather']

    except IOError:
        return 'IOERROR'


url = 'https://way.jd.com/he/freeweather?'


error_code = {'10001':'错误的请求appkey',
        '11010':'接口调用异常,稍后再试',
        '11030':'接口返回格式有误',
        '10003':'不存在对应数据',
        '10010':'接口需要付费',
        '10020':'万象系统繁忙,稍后再试',
        '10040':'超过每日限量',
        '10050':'用户被禁用'}

#city = 'changzhou'


def get_weather_city(city) -> str:
    key = getKey()
    if key == 'IOERROR':
        return 'IOERROR'
    param = {
            'city': city,
            'appkey': key
        }
    req = requests.get(url,param)
    res = req.json()

    codes = res['code']
    yin =  ''
    if codes != '10000':
        try:
            error_code['codes']
        except:
            return '发生了一个错误\n'+codes
        return '发生了一个错误\n'+error_code['codes']

    msg = res['msg'] #状态
    res_list = res['result']['HeWeather5']
    res_len = len(res_list)
    word = msg+'\n返回'+str(res_len)+'个结果\n--------' #待生成的句子

    for i in range(len(res_list)):
        res_city = res_list[i]['basic']['city'] #城市名
        res_country = res_list[i]['basic']['cnty'] #国家
        res_update = res_list[i]['basic']['update']['loc'] #更新时间
        res_text = res_list[i]['daily_forecast'][1]['cond']['txt_d']+'-'+res_list[i]['daily_forecast'][1]['cond']['txt_n']
        # 天气 A-B
        res_max = res_list[i]['daily_forecast'][1]['tmp']['max'] #最高温度
        res_min = res_list[i]['daily_forecast'][1]['tmp']['min']  #  最低温度

        word += '\n城市:'+res_country+res_city+'\n更新时间:'+res_update+'\n天气:'+res_text+'\n温度:'+res_min+'-'+res_max+'\n--------'

    return word

#print(word)
#print(res)
if __name__ == "__main__":
    print(get_weather_city('changzhou'))
